package com.test.webdemo.socket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(progressWebSocketHandler(), "/webdemo/progress")
                .setAllowedOrigins("*").setHandshakeHandler(handshakeHandler()); // 允许所有来源
    }

    @Bean
    public WebSocketHandler progressWebSocketHandler() {
        return new ProgressWebSocketHandler();
    }

    @Bean
    public HandshakeHandler handshakeHandler() {
        DefaultHandshakeHandler handler = new DefaultHandshakeHandler();
        handler.setSupportedProtocols("websocket"); // 强制协议
        return handler;
    }
}
